package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Constants;
import com.example.common.HttpStatusEnum;
import com.example.config.ConfigTableValueConfig;
import com.example.entity.ResponseData;
import com.example.pojo.Essay;
import com.example.mapper.EssayMapper;
import com.example.util.FileUtil;
import org.springframework.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文章信息表(Essay)表服务实现类
 *
 * @email: pengyujun53@163.com
 * @author: peng_YuJun
 * @date: 2024/01/17
 * @time: 23:13
 */
@Service
public class EssayService {
    /**
     * mapper对象
     */
    @Resource
    private EssayMapper essayMapper;
    // 系统配置参数
    @Resource
    private ConfigTableValueConfig configValue;

    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @param essay       筛选条件
     * @return
     */
    public ResponseData getByPage(Integer currentPage, Integer pageSize, Essay essay) {
        LambdaQueryWrapper<Essay> lqw = new LambdaQueryWrapper<>();
        //lqw查询条件构建
        lqw.like(StringUtils.hasText(essay.getTitle()), Essay::getTitle, essay.getTitle());
        lqw.like(StringUtils.hasText(essay.getAuthor()), Essay::getAuthor, essay.getAuthor());
        lqw.like(StringUtils.hasText(essay.getType()) && !essay.getType().equals("-1"), Essay::getType, essay.getType());
        lqw.like(!Arrays.asList(-1, null).contains(essay.getStatus()), Essay::getStatus, essay.getStatus());
        lqw.like(!Arrays.asList(-1, null).contains(essay.getAlarm()), Essay::getAlarm, essay.getAlarm());
        // 查询
        IPage ipage = new Page(currentPage, pageSize);
        essayMapper.selectPage(ipage, lqw);
        //若当前页码大于总页面数
        if (currentPage > ipage.getPages()) {
            ipage = new Page(ipage.getPages(), pageSize);
            essayMapper.selectPage(ipage, lqw);
        }
        if (ipage.getTotal() <= 0) {
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), ipage);
    }

    /**
     * 根据ID查询信息
     *
     * @param id 主键
     * @return 单条数据
     */
    public ResponseData findById(Long id) {
        Essay essay = essayMapper.selectById(id);
        if (essay == null || essay.getId() == null) {
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        //读取文件内容，赋值
        essay.setContent(FileUtil.readTextFile(configValue.getEssayTxtStorePath(), essay.getContent().replace(configValue.getEssayTxtNetUrl() + Constants.FORWARD_SLASH, "")));
        //返回结果
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), essay);
    }

    /**
     * 新增数据
     *
     * @param essay 实体
     * @return 新增结果
     */
    public ResponseData add(MultipartFile file, Essay essay) {
        //保存图片
        String pic = FileUtil.storeFile(file, configValue.getEssayCoversStorePath(), false);
        //保存内容到文件
        String contentFile = FileUtil.writeTextFile(essay.getContent(), configValue.getEssayTxtStorePath(), false, null);
        // 判断是否保存成功
        if (!StringUtils.hasText(pic) || !StringUtils.hasText(contentFile)) {
            return new ResponseData(HttpStatusEnum.ERROR.getCode(), "新增失败，请稍后再试");
        }
        // 保存成功
        essay.setContent(configValue.getEssayTxtNetUrl() + Constants.FORWARD_SLASH + contentFile);
        essay.setCover(configValue.getEssayCoversNetUrl() + Constants.FORWARD_SLASH + pic);
        //插入
        if (essayMapper.insert(essay) > 0) {
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "新增失败，请稍后再试");
    }

    /**
     * 更新数据
     *
     * @param essay 实体
     * @return 更新结果
     */
    public ResponseData update(MultipartFile file, Essay essay) {
        Essay essayTemp = essayMapper.selectById(essay.getId());
        //替换图片
        if (FileUtil.isMultipartFile(file)) {
            String pic = FileUtil.storeFile(file, configValue.getEssayCoversStorePath(), false);
            // 判断是否保存成功
            if (!StringUtils.hasText(pic)) {
                return new ResponseData(HttpStatusEnum.ERROR.getCode(), "更新失败，请稍后再试");
            }
            // 删除原有的
            String[] splitTemp = essayTemp.getCover().split(Constants.FORWARD_SLASH);
            FileUtil.deleteFile(configValue.getEssayCoversStorePath() + File.separator, splitTemp[splitTemp.length - 1]);
            // 写入新的照片链接
            essay.setCover(configValue.getEssayCoversNetUrl() + Constants.FORWARD_SLASH + pic);
        }
        // 更新内容到文件
        String contentFile = FileUtil.writeTextFile(essay.getContent(), configValue.getEssayTxtStorePath(), true,
                essayTemp.getContent().replace(configValue.getEssayTxtNetUrl() + Constants.FORWARD_SLASH, ""));
        if (!StringUtils.hasText(contentFile)) {
            return new ResponseData(HttpStatusEnum.ERROR.getCode(), "更新失败，请稍后再试");
        }
        essay.setContent(configValue.getEssayTxtNetUrl() + Constants.FORWARD_SLASH + contentFile);
        // 更新时间
        essay.setUtime(new Date());
        //更新
        if (essayMapper.updateById(essay) > 0) {
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "修改失败，请稍后再试");
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return
     */
    public ResponseData delete(Long id) {
        if (essayMapper.deleteById(id) > 0) {
            //返回成功响应
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "删除失败，请稍后再试");
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    public ResponseData deleteBatch(List<Long> idList) {
        if (essayMapper.deleteBatchIds(idList) > 0) {
            //返回成功响应
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "删除失败，请稍后再试");
    }

    /**
     * 上传文章图片
     *
     * @param file
     * @return
     */
    public ResponseData uploadEssayPic(MultipartFile file) {
        //保存图片
        String pic = FileUtil.storeFile(file, configValue.getEssayPicsStorePath(), false);
        // 判断是否保存成功
        if (!StringUtils.hasText(pic)) {
            return new ResponseData(HttpStatusEnum.ERROR.getCode(), "上传失败，请稍后再试");
        }
        pic = configValue.getEssayPicsNetUrl() + Constants.FORWARD_SLASH + pic;
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), pic);
    }

    /**
     * 获取全部正式发布的文章
     * @return
     */
    public ResponseData getAllValidEssay() {
        LambdaQueryWrapper<Essay> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Essay::getStatus, 2);
        List<Essay> essays = essayMapper.selectList(lqw);
        // 返回结果
        if (essays == null || essays.isEmpty()){
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), essays);
    }

    /**
     * 统计文章数
     * @return
     */
    public ResponseData countAll() {
        Long all = essayMapper.selectCount(null);
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), all);
    }
}
